1 /*
2 * Copyright (C) 2008 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.common.collect;
18
19 import com.google.common.annotations.GwtCompatible;
20 import com.google.common.primitives.Ints;
21
22 import javax.annotation.Nullable;
23
24 /**
25 * Static methods for implementing hash-based collections.
26 *
27 * @author Kevin Bourrillion
28 * @author Jesse Wilson
29 * @author Austin Appleby
30 */
31 @GwtCompatible
32 final class Hashing {
33 private Hashing() {}
34
35 private static final int C1 = 0xcc9e2d51;
36 private static final int C2 = 0x1b873593;
37
38 /*
39 * This method was rewritten in Java from an intermediate step of the Murmur hash function in
40 * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which contained the
41 * following header:
42 *
43 * MurmurHash3 was written by Austin Appleby, and is placed in the public domain. The author
44 * hereby disclaims copyright to this source code.
45 */
46 static int smear(int hashCode) {
47 return C2 * Integer.rotateLeft(hashCode * C1, 15);
48 }
49
50 static int smearedHash(@Nullable Object o) {
51 return smear((o == null) ? 0 : o.hashCode());
52 }
53
54 private static int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO;
55
56 static int closedTableSize(int expectedEntries, double loadFactor) {
57 // Get the recommended table size.
58 // Round down to the nearest power of 2.
59 expectedEntries = Math.max(expectedEntries, 2);
60 int tableSize = Integer.highestOneBit(expectedEntries);
61 // Check to make sure that we will not exceed the maximum load factor.
62 if (expectedEntries > (int) (loadFactor * tableSize)) {
63 tableSize <<= 1;
64 return (tableSize > 0) ? tableSize : MAX_TABLE_SIZE;
65 }
66 return tableSize;
67 }
68
69 static boolean needsResizing(int size, int tableSize, double loadFactor) {
70 return size > loadFactor * tableSize && tableSize < MAX_TABLE_SIZE;
71 }
72 }